<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AiCharacter;
use App\Models\TrainingScenario;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class TrainingController extends Controller
{
    /**
     * 获取AI角色列表
     */
    public function characters(Request $request)
    {
        $cacheKey = 'ai_characters_' . md5($request->getQueryString());
        
        $characters = Cache::remember($cacheKey, 3600, function () use ($request) {
            $query = AiCharacter::active();

            // 按难度筛选
            if ($request->has('difficulty')) {
                $query->byDifficulty($request->difficulty);
            }

            // 按标签筛选
            if ($request->has('tags')) {
                $tags = explode(',', $request->tags);
                foreach ($tags as $tag) {
                    $query->where('tags', 'like', '%' . trim($tag) . '%');
                }
            }

            return $query->orderBy('difficulty_level')
                        ->orderBy('name')
                        ->get();
        });

        $formattedCharacters = $characters->map(function ($character) {
            return [
                'id' => $character->id,
                'name' => $character->name,
                'personality_type' => $character->personality_type,
                'description' => $character->description,
                'difficulty_level' => $character->difficulty_level,
                'difficulty_text' => $character->difficulty_text,
                'avatar_url' => $character->avatar_url,
                'tags' => $character->tags_array,
            ];
        });

        return $this->success($formattedCharacters, '获取AI角色列表成功');
    }

    /**
     * 获取训练场景列表
     */
    public function scenarios(Request $request)
    {
        $cacheKey = 'training_scenarios_' . md5($request->getQueryString());
        
        $scenarios = Cache::remember($cacheKey, 3600, function () use ($request) {
            $query = TrainingScenario::active();

            // 按难度筛选
            if ($request->has('difficulty')) {
                $query->byDifficulty($request->difficulty);
            }

            // 按角色ID筛选（可以根据角色推荐合适的场景）
            if ($request->has('character_id')) {
                $character = AiCharacter::find($request->character_id);
                if ($character) {
                    // 推荐相近难度的场景
                    $query->whereBetween('difficulty_level', [
                        max(1, $character->difficulty_level - 1),
                        min(5, $character->difficulty_level + 1)
                    ]);
                }
            }

            // 按标签筛选
            if ($request->has('tags')) {
                $tags = explode(',', $request->tags);
                foreach ($tags as $tag) {
                    $query->where('tags', 'like', '%' . trim($tag) . '%');
                }
            }

            return $query->orderBy('difficulty_level')
                        ->orderBy('name')
                        ->get();
        });

        $formattedScenarios = $scenarios->map(function ($scenario) {
            return [
                'id' => $scenario->id,
                'name' => $scenario->name,
                'description' => $scenario->description,
                'objective' => $scenario->objective,
                'difficulty_level' => $scenario->difficulty_level,
                'difficulty_text' => $scenario->difficulty_text,
                'tags' => $scenario->tags_array,
                'success_criteria' => $scenario->success_criteria,
            ];
        });

        return $this->success($formattedScenarios, '获取训练场景列表成功');
    }

    /**
     * 收藏AI角色
     */
    public function favoriteCharacter(AiCharacter $character, Request $request)
    {
        $user = $request->user();

        if ($user->favoriteCharacters()->where('character_id', $character->id)->exists()) {
            return $this->error('已经收藏过这个角色了', 400);
        }

        $user->favoriteCharacters()->attach($character->id);

        return $this->success(null, '收藏成功');
    }

    /**
     * 取消收藏AI角色
     */
    public function unfavoriteCharacter(AiCharacter $character, Request $request)
    {
        $user = $request->user();

        if (!$user->favoriteCharacters()->where('character_id', $character->id)->exists()) {
            return $this->error('还没有收藏这个角色', 400);
        }

        $user->favoriteCharacters()->detach($character->id);

        return $this->success(null, '取消收藏成功');
    }
}